<?php

class Webmix_IndexController extends Core_Controller_Action_Standard
{
public function getFixPhotoURL($url) {
	$po = strpos($url, '?');
	if ($po!==FALSE) {
		$url = substr($url, 0, $po);
	}
	return $url;
}
	public function testAction(){
		$tb =  Engine_Api::_()->getDbTable('files', 'storage');
		$datas = $tb->fetchAll($tb->select()->where('parent_type=?', 'webmix_company')->where('type=?', 'thumb.normal'));
	foreach ($datas as $item){
		 $company =  Engine_Api::_()->getItemTable('webmix_company');
		$company = $company->fetchRow($company->select()->where('photo_id=?', $item->parent_file_id)->limit(1));
		
		if(!$company) continue;
		
		$host =  $_SERVER['HTTP_HOST'];
		$t_host = 'http://';
		$thumbnail =  $t_host.$host.$this->getFixPhotoURL($item->map());
	    $ext = ltrim(strrchr($thumbnail, '.'), '.');
        $thumbnail_parsed = @parse_url($thumbnail);
      if( @GetImageSize($thumbnail) ) {
        $valid_thumb = true;
      } else {
        $valid_thumb = false;
      }

      if( $valid_thumb && $thumbnail && $ext && $thumbnail_parsed && in_array($ext, array('jpg', 'jpeg', 'gif', 'png')) ) {
      	$tmp_file = APPLICATION_PATH . '/temporary/link_'.md5($thumbnail).'.'.$ext;
        $thumb_file = APPLICATION_PATH . '/temporary/link_thumb_'.md5($thumbnail).'.'.$ext;

        $src_fh = fopen($thumbnail, 'r');
        $tmp_fh = fopen($tmp_file, 'w');
        stream_copy_to_stream($src_fh, $tmp_fh, 1024 * 1024 * 2);

        $image = Engine_Image::factory();
        $image->open($tmp_file)
          ->resize(83, 83)
          ->write($thumb_file)
          ->destroy();

        try {
          $thumbFileRow = Engine_Api::_()->storage()->create($thumb_file, array(
            'parent_type' => $item->parent_type,
            'parent_id' => $item->parent_id,
          	'parent_file_id' => $item->parent_file_id
          ));

          $company->photo_id = $thumbFileRow->getIdentity();
          $company->save();
          
          $item->delete();
          // Remove temp file
          @unlink($thumb_file);
          @unlink($tmp_file);
        } catch( Exception $e ) {
          
        }
	}
	}
	die;
}
			
  public function indexAction()
  {
    
    if( !$this->_helper->requireUser()->isValid() ) {
           $this->view->error = true;
           return;
    }
    $viewer = Engine_Api::_()->user()->getViewer();
    
    $this->view->viewer = $viewer;
    $wbc = $this->_getParam('wbc',0);
    //echo '<pre>'.print_R($this->_getAllParams(),true)."</pre>";die;
    $webmixTable = Engine_Api::_()->getDbtable('webmixes','webmix');
    
   // echo $wbc;die;
    if(!empty($wbc)){
        $hadWebmixId = $webmixTable->hadWebixId($viewer->user_id,$wbc);
       
        if(!$hadWebmixId){
            $wbc = Engine_Api::_()->getItem('webmixes',$wbc);
            if($wbc && !empty($wbc->country_id)){
                $row = $webmixTable->createRow();
                $row->title = $wbc->title;
                $row->type = Webmix_Model_Webmix::WEBMIX_TYPE_USER;
                $row->owner_id = $viewer->user_id;
                $row->country_id = $wbc->country_id;
                $row->parent_id = $wbc->webmix_id;
                $row->save();
                $this->view->rendertab = $row->webmix_id;
            }
            
            
        }
        else{
            $this->view->rendertab = $hadWebmixId;
        }
        
        
        
        
    }
    
    
    
    $webmixs = $webmixTable->getWebmixsByUser();
    $this->view->webmixs = $webmixs;
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('webmix_main', array(), 'webmix_main_view');
      $this->view->webmix_id = 2;
  }
  
  public function deleteAction(){
     if( !$this->_helper->requireUser()->isValid() ) {
           $this->view->error = true;
           return;
      }
      $webmix_id = $this->_getParam('webmix_id',0);
      if(empty($webmix_id)) {
            $this->view->error = true;
            return $this->_forward('success', 'utility', 'core', array(
           	        'smoothboxClose' => false,
           	        'parentRefresh' => false,
           	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You can not delete this webmix'))
           ));
      }
      $viewer = Engine_Api::_()->user()->getViewer();
      $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
      if(!$webmix) {
            $this->view->error = true;
            return $this->_forward('success', 'utility', 'core', array(
           	        'smoothboxClose' => false,
           	        'parentRefresh' => false,
           	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You can not delete this webmix'))
           ));
      }
      
      if($webmix->content_type == Webmix_Api_Core::WEBMIX_CONTENT_TYPE_MUSIC ){
           return $this->_forward('success', 'utility', 'core', array(
           	        'smoothboxClose' => false,
           	        'parentRefresh' => false,
           	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You can not delete this webmix'))
           ));
      }
      
      if($webmix->owner_id != $viewer->user_id && $webmix->type =='user'){
            $this->view->error = true;
            return $this->_forward('success', 'utility', 'core', array(
           	        'smoothboxClose' => false,
           	        'parentRefresh' => false,
           	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You can not delete this webmix'))
           ));
      }
      if(!empty($webmix->default)) {
        $webmixT = Engine_Api::_()->getDbtable('webmixes','webmix');
        $hadUserDefault = $webmixT->existUserDefault($viewer->user_id);
        if($webmix->type =='user' ||  $hadUserDefault == false){
            $this->view->error = true;
            return $this->_forward('success', 'utility', 'core', array(
               	        'smoothboxClose' => false,
               	        'parentRefresh' => false,
               	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You can not delete this webmix'))
               ));
        }
        
      }
      $this->view->form  = $form = new Webmix_Form_Webmix_Default();
      $form->setTitle('Delete Webmix');
      $form->setDescription('Are you sure you want to delete this webmix?');
      if(!$this->getRequest()->isPost()) {
        return;
      }
      if($webmix->type !='system'){
          //update company count if not country-webmix
          if($webmix->parent_id == 0){
            //Call hook to delete block and
            $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('deleteBlockofWebmix', array(
              'webmix' => $webmix->webmix_id,
            ));        
          }
          $webmix->delete();
      }
      else{
          $deleteT = Engine_Api::_()->getDbtable('deletes','webmix');
          $row = $deleteT->createRow();
          $row->user_id = $viewer->user_id;
          $row->save();
      }
      
      $this->view->error  = false;
      return $this->_forward('success', 'utility', 'core', array(
       	        'parentRedirectTime' => 10,
       	        'parentRedirect' => $this->view->url(array(),'webmix_special',true),
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('webmix has been successfully deleted!'))
      ));
      
      
  }
  public function renameAction(){
      if( !$this->_helper->requireUser()->isValid() ) {
           $this->view->error = true;
           return;
      } 
      $webmix_id = $this->_getParam('webmix_id',0);
      if(empty($webmix_id)) {
            $this->view->error = true;
            return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => 1000,
       	        'parentRefresh' => false,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You can not rename this webmix!'))
       	    ));
      }
      $viewer = Engine_Api::_()->user()->getViewer();
      $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
      if(!$webmix) {
            $this->view->error = true;
            return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => 1000,
       	        'parentRefresh' => false,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You can not rename this webmix!'))
       	    ));
      }
      
      if($webmix->owner_id != $viewer->user_id){
            $this->view->error = true;
            return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => 1000,
       	        'parentRefresh' => false,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You can not rename this webmix!'))
       	    ));
      }
      $this->view->form  = $form = new Webmix_Form_Webmix_Rename();
      if(!$this->getRequest()->isPost()) {
        $form->webmix_name->setValue( $webmix->title);
        return;
      }
      
      if(!$form->isValid($this->getRequest()->getPost())){
        return;
      }
      $values = $form->getValues();
      $db = Engine_Db_Table::getDefaultAdapter();
      $db->beginTransaction();
      try{
        
        $webmix->title = $values['webmix_name'];
        $webmix->save();
        
        $db->commit();
        
        $this->view->error = false;
        $this->view->webmix_id = $webmix->webmix_id;
        
        $this->view->urlR = $this->view->url(array('module'=>'webmix','controller'=>'index','action'=>'index','webmix'=>$webmix->webmix_id),'default',true);
        return;
      }
      catch(Exception $e){
        $db->rollBack();
        $this->view->error = true;
      }
      
  }
  public function saveAction(){
      if( !$this->_helper->requireUser()->isValid() ) {
           $this->view->error = true;
           return;
      }  
      $x = $this->_getParam('x',0);
      $y = $this->_getParam('y',0);
     
      $webmix_id = $this->_getParam('webmix_id',0);
      if(empty($webmix_id)) {
            $this->view->error = true;
            $this->view->webmix  = true;
            return;
      }
      
      $block_id = $this->_getParam('block_id',0);
      if(empty($block_id)){
            $this->view->error = true;
            $this->view->block_id  = true;
            return;
      }
      
      $viewer = Engine_Api::_()->user()->getViewer();
      $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
      if(!$webmix) {
            $this->view->error = true;
             $this->view->webmix_id  = true;
            return;
      }
      
      if($webmix->owner_id != $viewer->user_id){
            $this->view->error = true;
             $this->view->viewer  = true;
            return;
      }
      
      $block = Engine_Api::_()->getItem('webmix_block',$block_id);
      
      if(!$block){
            $this->view->error = true;
             $this->view->block_object  = true;
            return;
      }
      if($block->webmix_id != $webmix_id ){
         $this->view->error = true;
             $this->view->block_object  = true;
            return;
      }
      $db = Engine_Db_Table::getDefaultAdapter();
      $db->beginTransaction();
      try{
        
        $block->position_y = $x;
        $block->position_x = $y;
        $block->save();
        
        $db->commit();
        $this->view->error = false;
        
      }
      catch(Exception $e){
        $db->rollBack();
        $this->view->error = true;
      }
      
      
  }
  
  public function createAction(){
        if( !$this->_helper->requireUser()->isValid() ) {
           $this->view->error = true;
           return;
        }
        
        $viewer = Engine_Api::_()->user()->getViewer();
        $permissionsTable = Engine_Api::_()->getDbtable('permissions', 'authorization');
        $maxWebmix =  $permissionsTable->getAllowed('webmix', $viewer->level_id, 'max');
        $webmixTable = Engine_Api::_()->getDbtable('webmixes','webmix');
        $current_total = $webmixTable->getTotalWebmix($viewer->user_id);
        if($current_total > $maxWebmix ){
            return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => false,
       	        'parentRefresh' => false,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You can not create new webmix, Number your webmix is larger number of system allow. Please contact admin to create new webmix !'))
           	));
        }
        $this->view->form = $form = new Webmix_Form_Webmix_Create();
        if(!$this->getRequest()->isPost()) return;
        if(!$form->isValid($this->getRequest()->getPost())) return;
        
        
        $db = $webmixTable->getAdapter();
        $values = $form->getValues();
        if (!isset($values['content_type'])){
            $values['content_type'] = 0;
        }
        try{
            $row = $webmixTable->createRow();
            $row->title = $values['webmix_name'];
            $row->type = Webmix_Model_Webmix::WEBMIX_TYPE_USER;
            $row->content_type = $values['content_type'];
            $row->owner_id = $viewer->user_id;
            $row->country_id = 0;
            $row->save();
            $db->commit();
            
            $this->view->success = true;
            $this->view->message = Zend_Registry::get('Zend_Translate')->_('A New Webmix has been successfully created !');
            $this->view->webmix_id = $row->webmix_id;
           /* return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => 10,
       	        'parentRefresh' => 10,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('A New Webmix has been successfully created !'))
           	));*/
            //return $this->_helper->redirector->gotoRoute(array('action' => 'index'), 'webmix_special', true);
        }
        catch(Exception $e){
            $form->addError('There are error, please contact admin.');
            $db->rollBack();
        }
  }
  
  public function setdefaultAction(){
      if( !$this->_helper->requireUser()->isValid() ) {
           $this->view->error = true;
           return;
      }
      $webmix_id = $this->_getParam('webmix_id',0);
      if(empty($webmix_id)) {
            $this->view->error = true;
            return $this->_forward('success', 'utility', 'core', array(
           	        'smoothboxClose' => false,
           	        'parentRefresh' => false,
           	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You webmix not found.'))
           ));
      }
      $viewer = Engine_Api::_()->user()->getViewer();
      $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
      if(!$webmix) {
            $this->view->error = true;
            return $this->_forward('success', 'utility', 'core', array(
           	        'smoothboxClose' => false,
           	        'parentRefresh' => false,
           	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You webmix not found.'))
           ));
      }
      
      
      
      $this->view->form  = $form = new Webmix_Form_Webmix_Default();
      $form->setTitle('Set Default Webmix');
      $form->setDescription('Are you sure you want to set this webmix as default?');
      if(!$this->getRequest()->isPost()) {
        return;
      }
      
      if(!empty($webmix->default)) {
        $this->view->error = true;
        if($webmix->type =='system'){
              $webmixT = Engine_Api::_()->getDbtable('webmixes','webmix');
              $webmixT->unsetDefault($viewer->user_id,0);
              $deleteT = Engine_Api::_()->getDbtable('deletes','webmix');
              $user_id = $viewer->user_id;
              $sql = " user_id = $user_id";
              $deleteT->delete($sql);
              $this->view->error  = false;
              return $this->_forward('success', 'utility', 'core', array(
               	        'parentRedirectTime' => 10,
               	        'parentRedirect' => $this->view->url(array(),'webmix_special',true),
               	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('Webmix has been set as default!'))
              ));
      
        }
        
      }
      
      $webmixT = Engine_Api::_()->getDbtable('webmixes','webmix');
      $webmixT->unsetDefault($viewer->user_id,$webmix_id);
      $webmix->default =1;
      $webmix->save();
      $this->view->error  = false;
      return $this->_forward('success', 'utility', 'core', array(
       	        'parentRedirectTime' => 10,
       	        'parentRedirect' => $this->view->url(array(),'webmix_special',true),
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('Webmix has been set as default!'))
      ));
      
  }
  
  public function setadmindefaultAction(){
      if( !$this->_helper->requireUser()->isValid() ) {
           $this->view->error = true;
           return;
      }
      $viewer = Engine_Api::_()->user()->getViewer();
      
      $this->view->form  = $form = new Webmix_Form_Webmix_Default();
      $form->setTitle('Set Default Webmix');
      $form->setDescription('Are you sure to set this Webmix become Default webmix?');
      if(!$this->getRequest()->isPost()) {
        return;
      }
      
      $webmixT = Engine_Api::_()->getDbtable('webmixes','webmix');
      $webmixT->unsetDefault($viewer->user_id,$webmix_id);
      $deleteT = Engine_Api::_()->getDbtable('deletes','webmix');
      $user_id = $viewer->user_id;
      $sql = " user_id = $user_id";
      $deleteT->delete($sql);
      $this->view->error  = false;
      return $this->_forward('success', 'utility', 'core', array(
       	        'parentRedirectTime' => 10,
       	        'parentRedirect' => $this->view->url(array(),'webmix_special',true),
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('Set default Webmix has been successfully!'))
      ));
      
  }
  
  public function addfavouriteAction(){
      $viewer = Engine_Api::_()->user()->getViewer();
      if (!$viewer || empty($viewer->user_id)){
            return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => 1000,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('Please sign in to continue.'))
            ));
      }
      $key = $this->_getParam('key',0);
      $blockT = Engine_Api::_()->getDbtable('Blocks','webmix');
      $result =  $blockT->addMusicFavourite($key);
      if ($result == true){
            return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => 1000,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('Music has been added to your Music Mix.'))
            ));
      } 
      
      if ($result == false){
            return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => 1000,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('Coould not add this music'))
            ));
      }
  }
}

